import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)
// 配置请求的根路径
// axios.defaults.baseUrl = '/api'

export default new Vuex.Store({
  state: {
    // 是否登录
    islogin: JSON.parse(sessionStorage.getItem('islogin')),
    // 用户
    user: JSON.parse(sessionStorage.getItem('user')),
    // 用户地址列表
    address: JSON.parse(sessionStorage.getItem('address')),
    // // 添加到购物车中的商品
    cartGoods: [],
    // 全部分类列表
    cateList: [],
    // 全部商品列表
    goodsList: [],
    // 商品详情
    goodDetail: null,
    // 二级分类列表
    typeList: [],
    // 某二级分类下的商品列表
    goodsByTypeList: [],
    // 分类页中选中的分类标题
    isCateSelected: 0,
    // 分类页中选中的子分类标题
    isTypeSelected: 0,
    // 订单列表
    orderList: [],
    // 当前查看的订单
    currentOrder: null,
    // 订单详情
    orderDetail: []
  },
  mutations: {
    // 初始化分类列表
    initCateList (state, list) {
      state.cateList = list
    },
    // 初始化商品列表
    initGoodsList (state, list) {
      state.goodsList = list
    },
    // 初始化/修改地址
    initAddress (state, address) {
      if (address) {
        state.address = address
        sessionStorage.setItem('address', JSON.stringify(address))
      } else {
        state.address = null
        sessionStorage.removeItem('address')
      }
    },
    // 根据id查询商品(详情)
    getGoodDetail (state, id) {
      state.goodDetail = state.goodsList.filter(item => item.goods_id === id)[0]
    },
    // 点击切换一级分类
    changeCate (state, obj) {
      // 切换分类id和子分类id
      state.isCateSelected = obj.index
      state.isTypeSelected = 0
      // 获得相应的子分类列表和商品列表
      state.typeList = state.cateList.filter(item => item.cat_pid === obj.id)
      state.goodsByTypeList = state.goodsList.filter(item => item.cat_id === state.typeList[0].cat_id)
    },
    // 点击切换子分类
    changeType (state, obj) {
      // 切换子分类id
      state.isTypeSelected = obj.index
      // 获得对应商品列表
      state.goodsByTypeList = state.goodsList.filter(item => item.cat_id === obj.id)
    },
    // 登录
    login (state) {
      sessionStorage.setItem('islogin', true)
      state.islogin = JSON.parse(sessionStorage.getItem('islogin'))
      state.user = JSON.parse(sessionStorage.getItem('user'))
    },
    // 注销
    logout (state) {
      sessionStorage.setItem('islogin', false)
      state.islogin = JSON.parse(sessionStorage.getItem('islogin'))
      sessionStorage.removeItem('user')
      sessionStorage.removeItem('address')
    },
    // 添加商品至购物车
    addGoodsToCart (state, item) {
      const id = state.cartGoods.findIndex(x => x.goods_id === item.goods_id)
      if (id !== -1) {
        state.cartGoods[id].count++
      } else {
        // item.count = 1
        // item.isInCart = true
        Vue.set(item, 'count', 1)
        Vue.set(item, 'isInCart', true)
        state.cartGoods.push(item)
      }
    },
    // 将选中的商品移除出购物车
    deleteGoodsFromCart (state) {
      state.cartGoods = state.cartGoods.filter(item => item.isInCart === false)
    },
    // 增加购物车商品数量
    addGoods (state, itemId) {
      state.cartGoods.some(val => {
        if (val.goods_id === itemId) {
          val.count++
          return true
        }
      })
    },
    // 减少购物车商品数量 flag true 数量小于等于1,直接移出 false 数量减少
    reduceGoods (state, obj) {
      state.cartGoods.some((val, index, Goods) => {
        if (val.goods_id === obj.itemId) {
          if (obj.flag) {
            Goods.splice(index, 1)
            return true
          } else {
            val.count--
            return true
          }
        }
      })
    },
    // 切换购物车全部商品的选择状态
    changeSelectAll (state) {
      const flag = state.cartGoods.every(item => item.isInCart)
      if (flag) {
        state.cartGoods.forEach(item => {
          item.isInCart = false
        })
      } else {
        state.cartGoods.forEach(item => {
          item.isInCart = true
        })
      }
    },
    // 切换购物车指定商品的选择状态
    changeSelect (state, itemId) {
      state.cartGoods.some(val => {
        if (val.goods_id === itemId) {
          val.isInCart = !val.isInCart
          return true
        }
      })
    },
    // 清空购物车
    clearCart (state) {
      state.cartGoods = []
    },
    // 初始化订单列表
    initOrderList (state, list) {
      list.forEach(item => {
        item.goods_list = JSON.parse(item.goods_list)
      })
      state.orderList = list
    },
    // 获取订单详情列表
    getOrderDetail (state, id) {
      if (state.orderList) {
        const orders = state.orderList.filter(item => item.order_id === id)
        state.currentOrder = orders[0]
        const orderDetailList = []
        orders[0].goods_list.forEach(item => {
          const goods = state.goodsList.filter(x => x.goods_id === item.goods_id)[0]
          Vue.set(goods, 'count', item.count)
          orderDetailList.push(goods)
        })
        state.orderDetail = orderDetailList
      } else {
        return false
      }
    }
  },
  actions: {
    // 获取分类列表
    getCateList (context) {
      axios.get('/api/category').then(({ data }) => {
        context.commit('initCateList', data)
      })
    },
    // 获取商品列表
    getGoodsList (context) {
      axios.get('/api/goods').then(({ data }) => {
        data.forEach(value => {
          value.goods_imgs = value.goods_imgs.split(' ')
        })
        context.commit('initGoodsList', data)
      })
    },
    // 获取用户的订单列表
    getOrderList (context) {
      if (this.state.islogin && this.state.user) {
        axios.get('/api/cart/getorder/' + this.state.user.user_id).then(({ data }) => {
          context.commit('initOrderList', data)
        })
      }
    },
    // 获取用户的地址信息
    getUserAddress (context) {
      if (this.state.islogin && this.state.user) {
        axios.get(`/api/user/getaddress/${this.state.user.user_id}`).then(({ data: res }) => {
          context.commit('initAddress', res.data[0])
        })
      }
    }
  },
  getters: {
    // 一级分类列表
    topCateList (state) {
      return state.cateList.filter(item => item.cat_level === 0)
    },
    // 购物车被选中的商品总价
    amount (state) {
      let amount = 0
      state.cartGoods.forEach(item => {
        if (item.isInCart) {
          amount += parseFloat(item.goods_price).toFixed(1) * item.count
        }
      })
      return amount.toFixed(1)
    },
    // 购物车被选中的商品数量
    count (state) {
      let count = 0
      state.cartGoods.forEach(item => {
        if (item.isInCart) {
          count += item.count
        }
      })
      return count
    },
    // 购物车中的商品是否进行全选
    isInCartAll (state) {
      if (state.cartGoods.length && state.cartGoods.every(val => val.isInCart)) {
        return true
      } else {
        return false
      }
    },
    // 返回购物车中被选中的商品列表
    GoodsListInCart (state) {
      return state.cartGoods.filter(item => item.isInCart)
    },
    // 当前购物车的商品id和数量集合
    orderGoods (state) {
      const orderGoodsList = []
      state.cartGoods.forEach(item => {
        const obj = {}
        obj.goods_id = item.goods_id
        obj.count = item.count
        orderGoodsList.push(obj)
      })
      return orderGoodsList
    },
    // 首页假数据
    homeList (state) {
      return [state.goodsList, state.goodsList, state.goodsList, state.goodsList]
    }
  }
})
